// Intersection.cpp
//
#include "Intersection.h"

bool lineIntersection( const OpenGL::Math::dvec2 &a1, 
					   const OpenGL::Math::dvec2 &a2,
					   const OpenGL::Math::dvec2 &b1,
					   const OpenGL::Math::dvec2 &b2,
					   OpenGL::Math::dvec2 *out )
{
	const OpenGL::Math::dvec2 a( a2-a1 );
	const OpenGL::Math::dvec2 b( b2-b1 );
	const OpenGL::Math::dvec2 perpA( -a.y, a.x );
	const OpenGL::Math::dvec2 perpB( -b.y, b.x );

	const double d = OpenGL::Math::dot(perpA, b);
	if( OpenGL::Math::abs(d) < 1e-8 )
		return false;

	OpenGL::Math::dvec2 c( b2-a2 );
	double aa = OpenGL::Math::dot( perpA, c );
	double bb = OpenGL::Math::dot( perpB, c );

	if( d < 0 )
    {
        if( aa > 0 )	return false;
        if( bb > 0 )	return false;
        if( aa < d )	return false;
        if( bb < d )	return false;
    }
    else
    {
        if( aa < 0 )	return false;
        if( bb < 0 )	return false;
        if( aa > d )	return false;
        if( bb > d )	return false;
    }

	if( out )
	{
        const double t = 1.0 - (aa / d);
		
		*out = b1 + (b * t);
	}
    return true;

	//const double A1 = p1.y-p0.y;
	//const double B1 = p0.x-p1.x;
	//const double C1 = A1*p0.x+ B1*p0.y;

	//const double A2 = p3.y-p2.y;
	//const double B2 = p2.x-p3.x;
	//const double C2 = A2*p2.x+ B2*p2.y;

	//const double d  = A1*B2 - A2*B1;

	//if( fabs(d) < 1e-8 )
	//	return false;

	//out.x = (B2*C1 - B1*C2) / d;
	//out.y = (A1*C2 - A2*C1) / d;

	//const double minX = std::min( p0.x,p1.x );
	//const double maxX = std::max( p0.x,p1.x );
	//const double minY = std::min( p0.y,p1.y );
	//const double maxY = std::max( p0.y,p1.y );

	//if( out.x >= minX && out.x <= maxX &&
	//	out.y >= minY && out.y <= maxY )
	//	return true;
	//
	//return false;
}